<template>
  <a-drawer :visible="dialog.visible" width="100%" @cancel="onClose" @ok="onOk">
    <template #title>
      {{ dialog.title }}
    </template>
    <a-spin :loading="loading" dot style="height: 100%; width: 100%">
      <fc-designer ref="designer" />
    </a-spin>
  </a-drawer>
</template>

<script lang="ts" setup>
import useLoading from "@/hooks/useLoading";
import { WfForm } from "@/api/workflow/form/types";
import { addWfForm, getWfForm, updateWfForm } from "@/api/workflow/form";
import { Message } from "@arco-design/web-vue";

const designer = ref();

const { loading, setLoading } = useLoading(true);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ""
});

const form = ref<WfForm>({
  formId: undefined,
  formName: "",
  remark: "",
  rule: "",
  options: ""
});

/**
 * 展示表单
 * @param formId 表单ID
 */
const show = async (formId: number | string) => {
  setLoading(true);
  try {
    dialog.title = "Arco-Design表单设计器";
    dialog.visible = true;
    const res: any = await getWfForm(formId);
    if (res) {
      form.value = res.data;
      console.log(form.value);
      // 加载表单JSON规则
      designer.value.setRule(form.value.rule);
      designer.value.setOption(form.value.options);
    }
  } finally {
    setLoading(false);
  }
};

const onOk = async () => {
  setLoading(true);
  try {
    form.value.rule = designer.value?.getJson(); // 获取表单的生成规则
    form.value.options = designer.value?.getOptionsJson(); // 获取表单的配置
    let res;
    if (form.value.formId) {
      res = await updateWfForm(form.value);
    } else {
      res = await addWfForm(form.value);
    }
    Message.success(res.msg);
  } finally {
    setLoading(false);
    dialog.visible = false;
  }
};

const onClose = () => {
  dialog.visible = false;
  form.value = {
    formId: undefined,
    formName: "",
    remark: "",
    rule: "",
    options: ""
  };
  designer.value?.setRule([]);
  designer.value?.setOption({});
};

defineExpose({
  show
});
</script>
